package com.cakeclient;


import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.TabHost;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.SubMenu;
import com.actionbarsherlock.view.Window;
import com.cakeclient.Model.*;
import com.cakeclient.facebookmodel.SessionStore;
import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.Facebook;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;


public class MainActivity extends SherlockFragmentActivity {
    TabHost mTabHost;
    public static final int RETURN_CHOOSE_STORE_ACTIVITY = 0;
    TabManager mTabManager;
    public Basket basket = new Basket();


    // Variables d'intégration Facebook!
    public static final String APP_ID = "368227953233723";
    public Facebook mFacebook;
    public AsyncFacebookRunner mAsyncRunner;
    public Bitmap facebookImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        //setTheme(com.actionbarsherlock.sample.fragments.R.style.Theme_Sherlock_Light);
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splashscreen_layout);


        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
        mTabHost.setup();

        mTabManager = new TabManager(this, mTabHost, R.id.realtabcontent);

        mTabManager.addTab(mTabHost.newTabSpec("Welcome").setIndicator("welcome"),
                ClientWelcomeFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("Catalogue").setIndicator("catalog"),
                ClientCatalogFragment.class, null);
        mTabManager.addTab(mTabHost.newTabSpec("Basket").setIndicator("Basket"),
                ClientBasketFragment.class, null);


        if (savedInstanceState != null) {
            mTabHost.setCurrentTabByTag(savedInstanceState.getString("tab"));
        }

        setSupportProgressBarIndeterminateVisibility(false);


    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == RETURN_CHOOSE_STORE_ACTIVITY) {
            if (resultCode == RESULT_OK) {
                LaunchWelcomeFragment();
            } else if (resultCode == RESULT_CANCELED) {
                Toast.makeText(this, "A store is mandatory to use this application.", Toast.LENGTH_SHORT).show();
                finish();
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("tab", mTabHost.getCurrentTabTag());

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);    //To change body of overridden methods use File | Settings | File Templates.
        Store localStore = Store.getLocalStore(getBaseContext());
        if ((localStore == null) || (Parameters.getAskForStore(getApplicationContext()))) {
            (new dialogStoreUpdate()).execute(0);
        } else {
            LaunchWelcomeFragment();
        }


        mFacebook = new Facebook(APP_ID);
        mAsyncRunner = new AsyncFacebookRunner(mFacebook);

        SessionStore.restore(mFacebook, this);
    }

    @Override
    protected void onResume() {
        super.onResume();    //To change body of overridden methods use File | Settings | File Templates.
        updateFacebookInformation();
        if (mFacebook.isSessionValid()) {
            downloadAvatar();
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu1 = menu.addSubMenu("Action Item");
        subMenu1.add("Preferences").setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(MenuItem item) {
                Intent intent = new Intent(getApplicationContext(), MainParametersActivity.class);
                startActivity(intent);
                return true;
            }
        });

        MenuItem subMenu1Item = subMenu1.getItem();
        subMenu1Item.setIcon(R.drawable.ic_menu);
        subMenu1Item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);

        return super.onCreateOptionsMenu(menu);
    }


    // --------------------------Méthodes FB:
    public void updateFacebookInformation() {
        SessionStore.restore(mFacebook, this);
    }


    private synchronized void downloadAvatar() {
        AsyncTask<Void, Void, Bitmap> task = new AsyncTask<Void, Void, Bitmap>() {

            @Override
            public Bitmap doInBackground(Void... params) {
                URL fbAvatarUrl = null;
                Bitmap fbAvatarBitmap = null;
                String id = Parameters.getFacebookId(getApplicationContext());
                try {
                    fbAvatarUrl = new URL("http://graph.facebook.com/" + id + "/picture");
                    fbAvatarBitmap = BitmapFactory.decodeStream(fbAvatarUrl.openConnection().getInputStream());
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                    //To change body of catch statement use File | Settings | File Templates.
                }
                return fbAvatarBitmap;
            }

            @Override
            protected void onPostExecute(Bitmap result) {
                facebookImage = (result);
            }

        };
        task.execute();
    }


//
//    public void updateFacebookName()  {
//        mAsyncRunner.request("me", new SampleRequestListener());
//    }


    // --------------------------Fin Méthodes FB


    // Displaying product list

    public void LaunchProductFragment(View view) {
        (new dialogCatalogUpdate()).execute(0);
    }

    public void BackToCatalog(View view) {
        (new LaunchProductFragment()).execute();
    }


    public void LaunchWelcomeFragment() {
        new LaunchWelcomeFragment().execute();

    }

    public void LaunchBasketFragment() {
        (new LaunchBasketFragment()).execute();
    }


    public void LaunchProductCardFragment(ProductType productType) {
        LaunchProductCardFragment fragment = new LaunchProductCardFragment();
        fragment.productType = productType;
        fragment.execute();
    }

    public void onClickTest(View v) {
        final Intent i = new Intent(this, ClientStoreListDialogActivity.class);
        startActivity(i);
    }

    public void sendOrder(View v) {
        if (Client.getLocalClient(getApplicationContext()) == null) {

            Toast toast = Toast.makeText(getApplicationContext(), "Please, choose an acccount in settings", Toast.LENGTH_SHORT);
            toast.show();
        } else {
            new dialogSendOrder().execute(basket.toOrder(Client.getLocalClient(getApplicationContext()), new Address(), getApplicationContext()));
            //Addresse de livraison nulle pour le moment

            try
            {
                String msg = "I have just ordered";
                if (!basket.getProducts().isEmpty()){
                for (ProductType produc : basket.getProducts()) {
                    msg = msg +" " + produc.getName()+",";
                }          }
                else{
                    msg = "Enjoy ";
                }
                msg = msg + " with Cake@Home!";
                Bundle parameters = new Bundle();
                parameters.putString("message", msg);
                parameters.putString("description", "test test test");

                mFacebook.request("me/feed", parameters,
                        "POST");


            }
            catch (Exception e)
            {
                // TODO: handle exception
                 e.printStackTrace();
            }

            basket.getProducts().clear();
            LaunchBasketFragment();
        }

    }

    private class dialogStoreUpdate extends SyncTaskManager.storeUpdate {
        ProgressDialog progressDialog;

        public dialogStoreUpdate() {
            super(MainActivity.this);
        }

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(getContext(), "Getting stores", "Communication in progress...");
        }

        @Override
        protected void onPostExecute(Integer integer) {
            progressDialog.dismiss();
            Intent i = new Intent(MainActivity.this, ClientStoreListDialogActivity.class);
            startActivityForResult(i, RETURN_CHOOSE_STORE_ACTIVITY);
        }
    }


    private class dialogSendOrder extends SyncTaskManager.SendOrder {
        ProgressDialog progressDialog;

        public dialogSendOrder() {
            super(MainActivity.this);
        }

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(getContext(), "Envoie de commande", "Merci de votre confiance...");
        }

        @Override
        protected void onPostExecute(Integer integer) {
            progressDialog.dismiss();
        }
    }


    private class dialogCatalogUpdate extends SyncTaskManager.catalogUpdate {
        ProgressDialog progressDialog;

        public dialogCatalogUpdate() {
            super(MainActivity.this);
        }

        @Override
        protected void onPreExecute() {
            progressDialog = ProgressDialog.show(getContext(), "Récupération du Catalogue", "Communication en cours...");
        }

        @Override
        protected void onPostExecute(Integer integer) {
            progressDialog.dismiss();
            (new LaunchProductFragment()).execute();

        }
    }


    private class LaunchProductFragment extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientProductsFragment());


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }

    private class LaunchWelcomeFragment extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientWelcomeFragment());


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }


    private class LaunchProductCardFragment extends AsyncTask<String, Void, String> {
        ProductType productType;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    Fragment fragment = new ClientProductCardFragment();
                    mTabManager.loadNewFragment(fragment);
                    ((ClientProductCardFragment) fragment).setProduct(productType);

                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }

    private class LaunchBasketFragment extends AsyncTask<String, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();    //To change body of overridden methods use File | Settings | File Templates.
            setSupportProgressBarIndeterminateVisibility(true);

        }

        @Override
        protected String doInBackground(String... strings) {
            new Thread(new Runnable() {
                @Override
                public void run() {

                    mTabManager.loadNewFragment(new ClientBasketFragment());


                }
            }).start();
            return null;  //To change body of implemented methods use File | Settings | File Templates.
        }

        @Override
        protected void onPostExecute(String result) {
            setSupportProgressBarIndeterminateVisibility(false);

        }
    }


    // Tab Manager
    public static class TabManager implements TabHost.OnTabChangeListener {
        private final FragmentActivity mActivity;
        private final TabHost mTabHost;
        private final int mContainerId;
        private Fragment mLastLoadedFragment;
        private final HashMap<String, TabInfo> mTabs = new HashMap<String, TabInfo>();
        TabInfo mLastTab;


        static final class TabInfo {
            private final String tag;
            private final Class<?> clss;
            private final Bundle args;
            private Fragment fragment;


            TabInfo(String _tag, Class<?> _class, Bundle _args) {
                tag = _tag;
                clss = _class;
                args = _args;
            }
        }

        static class DummyTabFactory implements TabHost.TabContentFactory {
            private final Context mContext;

            public DummyTabFactory(Context context) {
                mContext = context;
            }

            @Override
            public View createTabContent(String tag) {
                View v = new View(mContext);
                v.setMinimumWidth(0);
                v.setMinimumHeight(0);
                return v;
            }
        }

        public TabManager(FragmentActivity activity, TabHost tabHost, int containerId) {
            mActivity = activity;
            mTabHost = tabHost;
            mContainerId = containerId;
            mTabHost.setOnTabChangedListener(this);
        }


        public void addTab(TabHost.TabSpec tabSpec, Class<?> clss, Bundle args) {
            tabSpec.setContent(new DummyTabFactory(mActivity));
            String tag = tabSpec.getTag();


            TabInfo info = new TabInfo(tag, clss, args);

            // Check to see if we already have a fragment for this tab, probably
            // from a previously saved state.  If so, deactivate it, because our
            // initial state is that a tab isn't shown.
            info.fragment = mActivity.getSupportFragmentManager().findFragmentByTag(tag);
            if (info.fragment != null && !info.fragment.isDetached()) {
                FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
                ft.detach(info.fragment);
                ft.commit();
            }

            mTabs.put(tag, info);
            mTabHost.addTab(tabSpec);
        }


        @Override
        public void onTabChanged(String tabId) {
            TabInfo newTab = mTabs.get(tabId);
            FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                    ft.detach(mLastTab.fragment);
                }
            }
            if (mLastLoadedFragment != null) {
                if (mLastLoadedFragment != null) {
                    ft.detach(mLastLoadedFragment);
                }
            }
            if (newTab != null) {
                if (newTab.fragment == null) {
                    newTab.fragment = Fragment.instantiate(mActivity,
                            newTab.clss.getName(), newTab.args);
                    ft.add(mContainerId, newTab.fragment, newTab.tag);
                } else {
                    ft.attach(newTab.fragment);
                }
            }

            mLastTab = newTab;
            ft.commit();
            mActivity.getSupportFragmentManager().executePendingTransactions();

        }


        public void loadNewFragment(Fragment fragment) {


            FragmentTransaction ft = mActivity.getSupportFragmentManager().beginTransaction();
            if (mLastTab != null) {
                if (mLastTab.fragment != null) {
                    ft.detach(mLastTab.fragment);
                }
            }
            if (mLastLoadedFragment != null) {
                if (mLastLoadedFragment != null) {
                    ft.detach(mLastLoadedFragment);
                }
            }
            ft.add(mContainerId, fragment);
            ft.commit();

            mLastLoadedFragment = fragment;
        }
    }

}
